<script setup>
import { onMounted, ref } from 'vue'
import {
  getUserDetailAPI,
  getUserMoneyAPI,
  updateUserMoneyAPI,
  getUserTransactionAPI,
  userUpdateAPI
} from '@/api/user'
import { useUserStore } from '@/stores'

const userStore = useUserStore()

const userDetail = ref({})
const getUserDetail = async () => {
  const res = await getUserDetailAPI({
    UserName: userStore.userInfo.userName
  })
  console.log('gerzl', res)

  userDetail.value = res.data
}
const showEditUserDetail = ref(false)
const editUserDetail = () => {
  showEditUserDetail.value = true
}
const sendEditUserDetail = async () => {
  const res = await userUpdateAPI(userDetail.value)
  if (res.data == 1) {
    showEditUserDetail.value = false
    getUserDetail()
    ElMessage.success('修改成功')
  } else {
    ElMessage.error('修改失败')
  }
}

const activeNames = ref(['3'])
const handleChange = (val) => {
  console.log(val)
}

const userMoeny = ref({})
const tempMoney = ref(0)
const password = ref('')
const showAdd = ref(false)
const showDraw = ref(false)
const getUserMoney = async () => {
  const res = await getUserMoneyAPI({
    UserName: userStore.userInfo.userName
  })
  userMoeny.value = res.data
}
const showWitch = ref(false)
const showAddMoney = () => {
  showWitch.value = true

  showAdd.value = true
}
const addMoney = async () => {
  const amount = Number(tempMoney.value)
  if (amount <= 0) {
    ElMessage.error('充值金额必须大于0')
    return
  }

  const res = await updateUserMoneyAPI({
    UserName: userStore.userInfo.userName,
    Money: amount + Number(userMoeny.value.Money)
  })

  if (res.data == 1) {
    ElMessage.success('充值成功')
    tempMoney.value = 0
    showAdd.value = false
    getUserMoney()
  } else {
    ElMessage.error('充值失败')
  }
}

const showDrawMoney = () => {
  showWitch.value = true
  showDraw.value = true
}
const drawMoney = async () => {
  const amount = Number(tempMoney.value)

  // 检查提现金额是否有效
  if (amount <= 0) {
    ElMessage.error('提现金额必须大于0')
    return
  }

  // 检查提现金额是否大于账户余额
  if (amount > Number(userMoeny.value.Money)) {
    ElMessage.error('提现金额大于账户余额')
    return
  }

  const res = await updateUserMoneyAPI({
    UserName: userStore.userInfo.userName,
    Money: Number(userMoeny.value.Money) - amount
  })

  if (res.data == 1) {
    ElMessage.success('提现成功')
    tempMoney.value = 0
    showDraw.value = false
    getUserMoney()
  } else {
    ElMessage.error('提现失败')
  }
}

const UserTransaction = ref([])
const getUserTransaction = async () => {
  const res = await getUserTransactionAPI({
    UserName: userStore.userInfo.userName
  })
  UserTransaction.value = res.data
  if (UserTransaction.value.length > pageSize.value) {
    nowPageInfo.value = UserTransaction.value.slice(index.value, end.value)
  } else {
    nowPageInfo.value = UserTransaction.value
  }
}
const keywords = ['扣除', '悬赏', '充值', '提现']
const highlightKeywords = (str) => {
  let result = str
  keywords.forEach((keyword) => {
    const regex = new RegExp(keyword, 'g')
    result = result.replace(
      regex,
      `<span class="highlight" style="background-color: yellow;
      font-weight: bold;">${keyword}</span>`
    )
  })
  return result
}
const convertISO8601ToSimplified = (isoString) => {
  // 使用Date对象解析ISO 8601时间字符串
  const date = new Date(isoString)

  // 获取年、月、日、小时和分钟（注意：不使用UTC方法）
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以需要+1
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')

  // 构建并返回转换后的时间字符串
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

onMounted(() => {
  getUserDetail()
  getUserMoney()
  getUserTransaction()
})
const currentPage = ref(1)
const pageSize = ref(10)
const index = ref((currentPage.value - 1) * pageSize.value)
const end = ref(index.value + pageSize.value)
const nowPageInfo = ref([])
const handleSizeChange = (val) => {
  pageSize.value = val
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value = val
  index.value = (currentPage.value - 1) * pageSize.value
  end.value = index.value + pageSize.value
  console.log(index.value, end.value)
  nowPageInfo.value = UserTransaction.value.slice(index.value, end.value)
}
</script>

<template>
  <!-- 个人信息 -->
  <el-descriptions title="个人信息" column="2" border>
    <el-descriptions-item>
      <template #label>
        <div class="cell-item">
          <el-icon>
            <user />
          </el-icon>
          用户名
        </div>
      </template>
      {{ userDetail.UserName }}
    </el-descriptions-item>
    <el-descriptions-item>
      <template #label>
        <div class="cell-item">账号</div>
      </template>
      {{ userDetail.UserAccount }}
    </el-descriptions-item>
    <el-descriptions-item>
      <template #label>
        <div class="cell-item">手机号</div>
      </template>
      {{ userDetail.UserPhoneNumber }}
    </el-descriptions-item>
    <el-descriptions-item>
      <template #label>
        <div class="cell-item">性别</div>
      </template>
      {{ userDetail.UserSex }}
    </el-descriptions-item>
    <el-descriptions-item>
      <template #label>
        <div class="cell-item">回答质量分数</div>
      </template>
      {{ userDetail.AnswerQualityScore}}
    </el-descriptions-item>
  </el-descriptions>
  <el-button type="primary" @click="editUserDetail">编辑个人资料</el-button>

  <!-- 个人资金 发布的问题和回答 -->
  <div class="demo-collapse">
    <el-collapse v-model="activeNames" @change="handleChange">
      <!-- 个人资金 -->
      <el-collapse-item title="我的资金" name="3" class="fabu-title" style="text-align: center">
        <div>我的零钱</div>
        <div class="my-money">￥{{userMoeny.Money }}</div>
        <el-button type="primary" @click="showAddMoney">充值</el-button>
        <el-button type="info" @click="showDrawMoney">提现</el-button>
        <el-table :data="nowPageInfo" border style="width: 100%; margin-top: 15px">
          <el-table-column label="交易原因" width="400">
            <template #default="scope">
              <span v-html="highlightKeywords(scope.row.MoneyReason)"> </span>
            </template>
          </el-table-column>
          <el-table-column label="交易金额">
            <template #default="scope">
              <span>
                {{ scope.row.Money.toFixed(2) + '元' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="交易时间">
            <template #default="scope">
              <span>
                {{ convertISO8601ToSimplified(scope.row.Time) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 100, 200, 300, 400]"
          layout="sizes, prev, pager, next"
          :total="UserTransaction.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          style="margin: 10px auto"
        />
      </el-collapse-item>
    </el-collapse>
  </div>
  <el-dialog v-model="showAdd" title="充值零钱" width="500">
    <el-form :model="addedQuestion">
      <el-form-item label="充值金额:">
        <el-input v-model="tempMoney" autocomplete="off" />
      </el-form-item>
      <el-button type="primary" @click="addMoney()">充 值</el-button>
    </el-form>
  </el-dialog>
  <el-dialog v-model="showDraw" title="零钱提现" width="500">
    <el-form :model="addedQuestion">
      <el-form-item label="提现金额:">
        <el-input v-model="tempMoney" autocomplete="off" />
      </el-form-item>
      <el-form-item label="账户密码:">
        <el-input v-model="password" autocomplete="off" type="password" />
      </el-form-item>
      <el-button type="primary" @click="drawMoney()">提 现</el-button>
    </el-form>
  </el-dialog>
  <el-dialog v-model="showWitch" title="请选择交易方式" width="500" height="500">
    <div
      @click="showWitch = false"
      style="
        text-align: center;
        height: 50px;
        line-height: 50px;
        margin: 20px;
        border-radius: 50px;
        background-color: #1bd66c;
      "
    >
      微信交易
    </div>
    <div
      @click="showWitch = false"
      style="
        text-align: center;
        height: 50px;
        line-height: 50px;
        margin: 20px;
        border-radius: 50px;
        background-color: #21a4ed;
      "
    >
      支付宝交易
    </div>
  </el-dialog>
  <el-dialog title="修改资料" v-model="showEditUserDetail" width="500">
    <el-form :model="userDetail" label-width="80px" class="login-form">
      <el-form-item label="账号" prop="UserAccount">
        <el-input v-model="userDetail.UserAccount" disabled></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="UserPassword">
        <el-input type="password" v-model="userDetail.UserPassword" show-password></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="UserName">
        <el-input v-model="userDetail.UserName" disabled></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="UserPhoneNumber">
        <el-input v-model="userDetail.UserPhoneNumber"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="UserSex">
        <el-input v-model="userDetail.UserSex"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="sendEditUserDetail()">确认修改</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
.fabu-title {
  font-size: 15px;
  font-weight: 700;
}
.card {
  position: relative;
}
.card-title {
  font-weight: 900;
  font-size: 20px;
  line-height: 20px;
  margin: 15px;
}
.my-money {
  font-size: 30px;
}
.name {
  font-size: 12px;
}
.tag {
  background-color: rgba(173, 216, 230, 0.5); /* 浅蓝色背景，透明度为50% */
  border-radius: 5px;
  padding: 5px;
  margin: 5px;
}
.newtag {
  margin: 0 5px;
}
.money {
  font-weight: 600;
}
.more {
  position: absolute;
  right: 20px;
  top: 5px;
  background-color: #f9f9f9;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 13px;
  border-radius: 40px;
  cursor: pointer;
}
.time {
  margin-left: 10px;
  font-size: 12px;
  line-height: 12px;
}
.status {
  margin-left: 20px;
}
.red {
  color: red;
}
.green {
  color: green;
}
.bule {
  color: blue;
}
.content {
  margin: 10px;
  font-size: 20px;
  font-weight: 500;
}
.user {
  margin-left: 10px;
  margin-top: 10px;
  font-size: 14px;
}
.grade {
  margin-left: 15px;
}
.more {
  position: absolute;
  right: 20px;
  top: 5px;
  background-color: #f9f9f9;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 13px;
  border-radius: 40px;
  cursor: pointer;
}
.settle-problem {
  float: right;
}
</style>
